<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-01-12 11:40:01
 * @Last Modified time: 2023-01-13 11:28:58
 */
namespace app\common\services\user;

use frank\base\BaseService;
use app\common\dao\user\UserDao;

/**
 * 用户注册服务
 * Class RegisterService
 */
class RegisterService extends BaseService
{
    /**
     * RegisterService constructor.
     * @param userDao $dao
     */
    public function __construct(UserDao $dao)
    {
        $this->dao = $dao;
    }

	/**
     * 注册
     * @param $data
     */
    public function authRegister($data,$appType = 'weapp'){
    	// 无授权名称则生成
    	if (isset($data[ 'nickName' ]) && !empty($data[ 'nickName' ])) {
            $nickname = preg_replace_callback('/./u',
                function(array $match) {
                    return strlen($match[ 0 ]) >= 4 ? '' : $match[ 0 ];
                },
                $data[ 'nickName' ]);
        }

        $dataReg = [
            'nickName' => $data[ 'nickName' ] ?? '新用户',
            'avatar'=> isset($data['avatarUrl']) ? $this->pullAvatar($data['avatarUrl']) : '',
            'last_login_time'=> time(),
            'register_source'=> $appType,
        ];
        $res = $this->dao->create($dataReg);
        if (!$res) throw new CommonException('新用户注册失败');
        return $res->id;
    }


    public function pullAvatar($url){
        $dirPath = app()->getRootPath() .'/public/uploads/image/user';
        !is_dir($dirPath) && mkdir($dirPath, 0755, true);
        $imgName = md5($url) . '.png';
        $imgUrl = baseUrl().'/uploads/image/user/'. $imgName;
        $savePath = $dirPath . '/' . md5($url) . '.png';
        if (file_exists($savePath)) return  $imgUrl;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $img = curl_exec($ch);
        curl_close($ch);
        $fp = fopen($savePath, 'w');
        fwrite($fp, $img);
        fclose($fp);
        return  $imgUrl;
    }
}